package router

import (
	"context"
	"github.com/aberic/gnomon/grope"
	"github.com/docker/docker/api/types/filters"
	"gykjgit.dccnet.com.cn/chain/swarm/client"
	"net/http"
	"time"
)

func RouteService(hs *grope.GHttpServe) {
	// 仓库相关路由设置
	route := hs.Group("/service")
	route.Get("/logs/:id/:since/:until", serviceLogs) // 20200518032852 20200518033200
	route.Get("/list", serviceList)
	route.Get("/process", serviceProcess)
	route.Get("/remove/:id", serviceRemove)
	route.Get("/inspect/:id", serviceInspect)
	route.Get("/resources/:id", serviceResources)
	route.Get("/resources", serviceResourcesAll)
}

func serviceLogs(ctx *grope.Context) {
	var (
		since, until time.Time
		bs           []byte
		err          error
	)
	since, err = time.Parse("20060102150405", ctx.Value("since"))
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	until, err = time.Parse("20060102150405", ctx.Value("until"))
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	bs, _ = client.Obtain().Service().Logs(context.Background(), ctx.Value("id"), since, until)
	_ = ctx.ResponseText(http.StatusOK, string(bs))
}

func serviceList(ctx *grope.Context) {
	services, err := client.Obtain().Service().List(context.Background())
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeSuccess, Data: services})
}

// Process List the tasks of one or more services
func serviceProcess(ctx *grope.Context) {
	services, err := client.Obtain().Service().Process(context.Background(), filters.NewArgs())
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeSuccess, Data: services})
}

// Remove Remove one or more services
func serviceRemove(ctx *grope.Context) {
	if err := client.Obtain().Service().Remove(context.Background(), ctx.Value("id")); nil != err {
		responseFailJSON(ctx, err)
		return
	}
	_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeSuccess})
}

func serviceInspect(ctx *grope.Context) {
	service, _, err := client.Obtain().Service().Inspect(context.Background(), ctx.Value("id"))
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeSuccess, Data: service})
}

func serviceResources(ctx *grope.Context) {
	resources, err := client.Obtain().Service().Resources(context.Background(), ctx.Value("id"))
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeSuccess, Data: resources})
}

func serviceResourcesAll(ctx *grope.Context) {
	resources, err := client.Obtain().Service().ResourcesAll(context.Background())
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeSuccess, Data: resources})
}
